package com.github.jave.process;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 *  收集执行结果 采用监听器模式 反馈给调用者
 */
public class NotifyProcess implements Runnable{
    private Process process;
    private List<ProcessListener> processListeners;

    public NotifyProcess(Process process,List<ProcessListener> processListeners) {
        this.process = process;
        this.processListeners=processListeners;
    }

    public void run() {
        try {
            notifyResult(process);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void notifyResult(Process process) throws IOException {
        successNotify(process);
        failNotify(process);
    }

    private void successNotify(Process process) throws IOException{
        InputStream inputStream = process.getInputStream();
        byte[] read = new byte[1024];
        while (inputStream.read(read) != -1){
            //TODO 待优化 解析换行符  每一行 调用一次
            for(ProcessListener listener:processListeners){
                listener.onSuccess(new String(read));
            }
            if(processListeners.isEmpty()){
                System.out.println(new String(read,"GBK"));
            }
        }
    }
    private void failNotify(Process process) throws IOException{
        InputStream errorStream = process.getErrorStream();
        byte[] read = new byte[1024];
        while (errorStream.read(read) != -1){
            //TODO 待优化 解析换行符  每一行 调用一次
            for(ProcessListener listener:processListeners){
                listener.onError(new String(read));
            }
            if(processListeners.isEmpty()){
                System.err.println(new String(read,"GBK"));
            }
        }
    }

}
